#!/usr/bin/env python
# -- coding: utf-8 --
# @Time : 2025/2/12 下午12:46
# @Author: wen
# @Email: happiness.sq@foxmail.com
# @README: 云擎取文件.py
import json
import time
import requests


class yunqing(object):
    def __init__(self, Access_Token):
        self.token = Access_Token
        self.session = requests.Session()
        self._initialize_session()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self._delete_session()

    def _initialize_session(self):
        self.session.headers = {
            "Accept": "application/json, text/plain, */*",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "Access-Token": self.token,
            "Authorization": "8HNiFyEvVTADBYq41yyL5CC8BdW93VJlPpUYyoP8LubnG8nChZmPwo+VJjcwSFUB",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Content-Type": "application/json;charset=UTF-8",
            "Origin": "http://172.17.42.211:9090",
            "Pragma": "no-cache",
            "Referer": "http://172.17.42.211:9090/wb/",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36 Edg/132.0.0.0",
            "accessId": "337",
            "poolCode": "gy",
            "poolId": "BJtZflvl",
            "token": self.token,
            "userId": "dwsongwen",
            "userName": "%E5%AE%8B%E6%96%87"
        }
        self.session.verify = False
        self.session.timeout = 15

    def _get_task_list(self):
        """查询云擎任务列表，进行删除云擎拷贝文件任务 """
        url = "http://172.17.42.211:9090/wb/api/v1/hostFileTask/getHostFileTaskList"
        data = {
            "page": 1,
            "rows": 50,
            "filter": {
                "taskState": 5,
                "taskType": 1,
                "poolIds": [
                    "BJtZflvl"
                ]
            }
        }
        data = json.dumps(data, separators=(',', ':'))
        response = self.session.post(url, data=data)
        rows = response.json()["result"]["rows"]
        return rows

    def add_task(self, FilePath):
        """添加云擎拷贝文件任务
        filePath:文件路径
        :return:任务id
        """
        url = "http://172.17.42.211:9090/wb/api/v1/hostFileTask/addHostFileTask"
        data = {
            "taskName": "file-cp",
            "taskDesc": "",
            "aimPath": "UbmWat6t",
            "credentialId": 10000333,
            "cronExeMode": 0,
            "periodValue": 1,
            "periodIdx": [],
            "sourceFilePath": FilePath,
            "hostType": 0,
            "hostInfo": [
                "121wi7POOy"
            ],
            "taskType": 1,
            "fileName": "file",
            "isPrivate": 1,
            "directoryId": "UbmWat6t",
            "poolId": "BJtZflvl",
            "targetPoolId": "BJtZflvl"
        }
        data = json.dumps(data, separators=(',', ':'))
        response = self.session.post(url, data=data)
        # print("add_task", response.json())
        if int(response.json()['code']) == 0:
            time.sleep(3)
            rows = self._get_task_list()
            for row in rows:
                if row["taskName"] == "file-cp":
                    if row['sourceFilePath'] == FilePath:
                        return row["hfId"]
        else:
            print(response.text)
            return False

    def _execTask(self, hfId):
        """根据hfid 执行云擎备份任务"""
        url = "http://172.17.42.211:9090/wb/api/v1/hostFileTask/execTask"
        data = {
            "hfId": hfId
        }
        data = json.dumps(data, separators=(',', ':'))
        response = self.session.post(url, data=data)
        # print("_execTask", response.json())
        # print(response)

    def _get_file_dir(self):
        """获取file目录的文件列表"""
        url = "http://172.17.42.211:9090/wb/api/v1/minio/getResourceList"
        data = {
            "fileName": "",
            "parentId": "UbmWat6t",
            "tagSet": [],
            "isPrivate": "1",
            "tenantId": 282
        }
        data = json.dumps(data, separators=(',', ':'))
        response = self.session.post(url, data=data)
        fileDirInfoOutputList = response.json()["result"]["fileDirInfoOutputList"]
        return fileDirInfoOutputList

    def _get_file_list(self):
        """获取file目录的文件列表"""
        fileDirInfoOutputList = self._get_file_dir()

        for fileDirInfoOutput in fileDirInfoOutputList:
            parentId = fileDirInfoOutput["id"]
            url = "http://172.17.42.211:9090/wb/api/v1/minio/getResourceList"
            data = {
                "fileName": "",
                "parentId": parentId,
                "tagSet": [],
                "isPrivate": "1",
                "tenantId": 282
            }
            data = json.dumps(data, separators=(',', ':'))
            response = self.session.post(url, data=data)
            if int(response.json()['code']) == 0:
                fileInfoOutputList = response.json()["result"]["fileInfoOutputList"]
                if len(fileInfoOutputList) == 0:
                    return False
                for fileInfoOutput in fileInfoOutputList:
                    fileId = fileInfoOutput["id"]
                    fileName = fileInfoOutput["fileName"]
                    return fileId, fileName

    def download_file(self, fileId, fileName):
        url = "http://172.17.42.211:9090/wb/api/v1//minio/downloadDocument"
        data = {
            "fileId": fileId,
            "tenantId": 282
        }
        data = json.dumps(data, separators=(',', ':'))
        response = self.session.post(url, data=data, verify=False)
        response.raise_for_status()

        with open(fileName, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                f.write(chunk)
            print(f"下载成功 {fileName}")

    def _getResourceList(self):
        """删除拷贝后的文件和目录"""
        fileDirInfoOutputList = self._get_file_dir()
        for fileDirInfoOutput in fileDirInfoOutputList:
            if fileDirInfoOutput["dirParentId"] == "UbmWat6t":
                url = "http://172.17.42.211:9090/wb/api/v1/minio/deleteFolder"
                json_data = [
                    fileDirInfoOutput['id'],
                ]
                response = self.session.post(url, json=json_data)
                if int(response.json()['code']) == 0:
                    # print("删除目录成功")
                    return True

    def _delete_session(self):
        """查询云擎任务列表，进行删除云擎拷贝文件任务 """
        rows = self._get_task_list()
        for row in rows:
            if row["taskName"] == "file-cp":
                hostFileTask = "http://172.17.42.211:9090/wb/api/v1/hostFileTask/deleteHostFileTask"
                json_data = json.dumps(row, separators=(',', ':'))
                res = self.session.post(hostFileTask, data=json_data)
                if int(res.json()['code']) == 0:
                    self._getResourceList()
                    # print("删除任务成功")

    def entrance(self, FilePath):
        # FilePath = '/data/maint2/GYDC-PUB-UNDEFINED03-ITC21_20250212.sds'
        hfId = self.add_task(FilePath)
        time.sleep(3)
        if hfId:
            self._execTask(hfId)
            time.sleep(3)
            while True:
                file_list = self._get_file_list()
                if not file_list:
                    time.sleep(5)
                    continue
                fileId, fileName = file_list
                self.download_file(fileId, fileName)
                return True
        else:
            print("请检查任务")

    def getHostScriptRecordOut(self, taskExecId):
        """获取云擎脚本执行结果状态"""
        url = "http://172.17.42.211:9090/wb/api/v1/task/getHostScriptRecordOut"
        data = {
            "page": 1,
            "rows": 50,
            "filter": {
                "taskExecId": taskExecId,
                "execStatus": 2
            }
        }
        data = json.dumps(data, separators=(',', ':'))
        response = self.session.post(url, data=data)
        if not response.json()["result"]["rows"]:
            return False
        execResult = response.json()["result"]["rows"][0]["execResult"]
        # print(execResult)
        return execResult.split('：')[1].strip()

    def task_execute(self, h3c_ipmi):
        """执行云擎sds脚本"""
        url = "http://172.17.42.211:9090/wb/api/v1/task/taskExecute"
        data = {
            "credentialId": 10000333,
            "hostInfo": [
                "121wi7POOy"
            ],
            "hostType": 0,
            "taskId": "3BSiRxfM",
            "versionId": 10006440,
            "tenantId": 282,
            "taskExecuteParamsInList": [
                {
                    "taskParamId": "aP8mqx17",
                    "paramType": 0,
                    "paramName": "ipmi_ip",
                    "paramVal": h3c_ipmi,
                    "paramInOut": 0,
                    "taskVerId": 10006440,
                    "versionName": "20250212180448",
                    "paramDesc": "",
                    "bucketName": None,
                    "fileId": None
                }
            ],
            "approvalType": 0,
            "interpreter": "/bin/sh",
            "executeType": 0
        }
        data = json.dumps(data, separators=(',', ':'))
        response = self.session.post(url, data=data)
        if int(response.json()['code']) == 0:
            try:
                taskExecId = response.json()['otherObj']
                while True:
                    execResult = self.getHostScriptRecordOut(taskExecId)
                    if execResult:
                        return execResult
                    else:
                        time.sleep(5)
            except Exception as e:
                print(e)
                print("执行失败", response.json())
        else:
            print(response.text)
            print(response.status_code)

    def yq_task(self, paramVal):
        """执行云擎sds清理堡垒机sds文件"""
        url = "http://172.17.42.211:9090/wb/api/v1/task/taskExecute"
        data = {
            "credentialId": 10000333,
            "hostInfo": [
                "121wi7POOy"
            ],
            "hostType": 0,
            "taskId": "BDh2VZgN",
            "versionId": 10006442,
            "tenantId": 282,
            "taskExecuteParamsInList": [
                {
                    "taskParamId": "gK2bWLsW",
                    "paramType": 0,
                    "paramName": "file_path",
                    "paramVal": paramVal,
                    "paramInOut": 0,
                    "taskVerId": 10006442,
                    "versionName": "20250212203142",
                    "paramDesc": "文件路径",
                    "bucketName": None,
                    "fileId": None
                }
            ],
            "approvalType": 0,
            "interpreter": "/bin/sh",
            "executeType": 0
        }
        data = json.dumps(data, separators=(',', ':'))
        response = self.session.post(url, data=data)
        if int(response.json()['code']) == 0:
            return True


def main(yq_token, ipmi):
    with yunqing(yq_token) as fetcher:
        file = fetcher.task_execute(ipmi)
        fetcher.entrance(file)
        fetcher.yq_task(file)


if __name__ == '__main__':
    token = '0ea7b211ea174e4ebc2e20c98aa76a30'
    h3c_ipmi = "10.126.115.3"
    main(token, h3c_ipmi)